package cn.netty.example3;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * 使用DelimiterBasedFrameDecoder对象解决粘包问题
 * <p>Title: EchoServer</p>
 * <p>Description: 自定义解码器的应用</p>
 * @version V1.0
 * @author ZhiPeng_Chen
 * @date: 2018/10/31
 */
public class EchoServer {

    private NioEventLoopGroup acceptorGroup;
    private NioEventLoopGroup workGroup;
    private ServerBootstrap serverBootstrap;

    private void init(){
        this.acceptorGroup = new NioEventLoopGroup();
        this.workGroup = new NioEventLoopGroup();
        this.serverBootstrap = new ServerBootstrap();
        this.serverBootstrap.group(acceptorGroup,workGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG,1024);

    }

    public EchoServer(){
        init();
    }

    /**
     * 使用"$_"作为分割符
     * 创建DelimiterBasedFrameDecoder对象 将他加入ChannelPipeline中
     * 传入两个参数一个是DelimiterBasedFrameDecoder另一个个1024
     * 单条消息长度过长就会抛出TooLongFrameException 用于防止异常流导致的内存溢出
     * @param port
     * @return
     * @throws InterruptedException
     */
    public ChannelFuture doAcceotor(int port) throws InterruptedException {


        this.serverBootstrap
                .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {

                    protected void initChannel(SocketChannel ch) throws Exception {

                        ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes());

                        //(重点代码)使用DelimiterBasedFrameDecoder自定义分割符号作为流结束标志
                        ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,delimiter));
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(new EchoServerHandle());

                    }
                });


        return serverBootstrap.bind(port).sync();
    }

    /**
     * 回收资源
     */
    public void release(){
        this.workGroup.shutdownGracefully();
        this.acceptorGroup.shutdownGracefully();
    }



    public static void main(String[] args) {
        EchoServer server = new EchoServer();
        ChannelFuture future = null;
        try {
            future = server.doAcceotor(8888);
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            System.out.println(e.getMessage());
        }finally {
            server.release();
        }
    }
}
